package cn.zn.modules.invoice.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.zn.framework.common.utils.PageUtils;
import cn.zn.framework.common.utils.R;
import cn.zn.modules.invoice.entity.InvoiceDetailEntity;
import cn.zn.modules.invoice.entity.dto.InvoiceDetailQueryDTO;
import cn.zn.modules.invoice.entity.dto.InvoiceDetailSaveDTO;
import cn.zn.modules.invoice.service.InvoiceDetailService;
import cn.zn.modules.zzsys.inter.annotation.Login;
import cn.zn.modules.zzsys.inter.annotation.LoginUser;
import cn.zn.modules.zzsys.inter.annotation.SysLog;
import cn.zn.modules.zzsys.inter.dto.LoginUserDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;


/**
 * 发票信息
 *
 * @author zn
 * @email zhunahao@qq.com
 * @date 2020-04-08 22:07:19
 */
@RestController
@RequestMapping("invoice/invoicedetail")
public class InvoiceDetailController {
    @Autowired
    private InvoiceDetailService invoiceDetailService;

    /**
     * 列表
     */
    @PostMapping("/list")
//    @RequiresPermissions("invoice:invoicedetail:list")
    public R list(@Valid @RequestBody InvoiceDetailQueryDTO invoiceDetailQueryDTO) {

        PageUtils pageUtils = invoiceDetailService.queryPage(invoiceDetailQueryDTO);

        return R.ok().put("page", pageUtils);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Login
    @SysLog("保存发票")
    //    @RequiresPermissions("invoice:invoicedetail:save")
    public R save(@LoginUser LoginUserDTO loginUser, @RequestBody @Valid InvoiceDetailSaveDTO invoiceDetailSave) {
        // 验证重复
        int count = invoiceDetailService.count(new QueryWrapper<InvoiceDetailEntity>()
                .eq("code", invoiceDetailSave.getCode())
                .eq("number", invoiceDetailSave.getNumber())
        );
        if (count > 0) {
            return R.error("此发票信息已经存在！");
        }
        // 保存信息
        InvoiceDetailEntity invoiceDetail = new InvoiceDetailEntity();
        BeanUtil.copyProperties(invoiceDetailSave, invoiceDetail);
        invoiceDetail.setCreateUser(Long.valueOf(loginUser.getWorkNo()));
        invoiceDetail.setUpdateUser(Long.valueOf(loginUser.getWorkNo()));
        invoiceDetailService.save(invoiceDetail);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("invoice:invoicedetail:delete")
    public R delete(@RequestBody Long[] ids) {
        invoiceDetailService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 删除
     */
    @DeleteMapping("/deleteByRecordCode")
    public R deleteByRecordCode(@RequestBody String recordCode) {
        invoiceDetailService.deleteByRecordCode(recordCode);

        return R.ok();
    }
}
